package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SpuDetailServiceImpl extends ServiceImpl<SpuDetailMapper, SpuDetail> implements SpuDetailService {

    @Resource
    private SpuService spuService;

    @Resource
    private SpecParamService specParamService;

    @Override
    public SpuDetailDTO queryGoodsDetailById(Long id) {
        return new SpuDetailDTO(this.getById(id));
    }

    @Override
    public List<SpecParamDTO> querySpecValues(Long id, Boolean searching) {
        // 1.准备规格参数value
        // 1.1.根据id查询spuDetail
        SpuDetail spuDetail = this.getById(id);

        //把规格属性从json转换为map，key为long即规格参数的id，value就是规格参数的值
        Map<Long, Object> specValues = JsonUtils.nativeRead(spuDetail.getSpecification(), new TypeReference<Map<Long, Object>>() {
        });
        // 1.2.获取其中的规格参数键值对，json转为一个map
        //Map<Long, Object> specValues = JsonUtils.toMap(spuDetail.getSpecification(), Long.class, Object.class);
        // 2.准备规格参数对象
        // 2.1.根据id查询spu，获取商品分类信息
        Spu spu = spuService.getById(id);
        // 2.2.根据分类id查询规格参数集合，如果searching不为空，还要加上searching条件
        List<SpecParamDTO> specParamDTOList = specParamService.querySpecParams(spu.getCid3(), null, searching);
        // 3.找到param的value，并存储
        for (SpecParamDTO param : specParamDTOList) {
            param.setValue(specValues.get(param.getId()));
        }
        log.info("goods_service:{}",specParamDTOList);
        return specParamDTOList;
    }
}
